package com.whj.service.impl;

import com.whj.domain.constants.SystemConstants;
import com.whj.domain.dto.LoginUserDTO;
import com.whj.domain.entity.LoginUser;
import com.whj.domain.enums.AppHttpCodeEnum;
import com.whj.domain.response.ResponseResult;
import com.whj.service.LoginService;
import com.whj.service.SystemLoginService;
import com.whj.utils.JwtUtil;
import com.whj.utils.RedisCache;
import com.whj.utils.SecurityUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @Auther: wanghaijun
 * @Date: 2023/5/30 - 05 - 30 - 10:11 
 * @Description: com.whj.service.impl
 */

@Service
public class SystemLoginServiceImpl implements SystemLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(LoginUserDTO loginUserDTO) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUserDTO.getUserName(), loginUserDTO.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        // 判断是否认证通过
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException(AppHttpCodeEnum.LOGIN_ERROR.toString());
        }
        // 获取userid 生成token
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Long id = loginUser.getUser().getId();
        String token = JwtUtil.createJWT(id.toString());
        // 把用户信息保存到redis中
        redisCache.setCacheObject("systemLogin:"+id,loginUser);
        System.out.println("token = " + token);
        Map<String, String> map = new HashMap<>();
        map.put("token",token);
        return ResponseResult.okResult(map);
    }

    /**
     * 退出登录 删除redis信息
     * @return
     */
    @Override
    public ResponseResult logout() {
        Long userId = SecurityUtils.getUserId();
        redisCache.deleteObject("systemLogin:"+userId);
        return ResponseResult.okResult();
    }

}
